<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Page_Services_Page
{
	const EOL = "\n";
	
	public static function factory()
	{
		$request = Gio_Core_Request::getInstance();
		$config = Gio_Core_Module::getConfig('page');
		$param = isset($config['url']['param']) ? $config['url']['param'] : 'page_id';
		$category = null;
		
		switch ($param) {
			case 'slug':
				$page = Modules_Page_Services_Page::getBySlug($request->getParam($param));
				break;
		}
		if (null == $page) {
			$page = Modules_Page_Services_Page::getById($request->getParam('page_id'));
		}
		
		return $page;
	}
	
	public static function validate($data)
	{
		$validator = new Gio_Core_Validator();
		foreach ($data as $index => $value) {
			if (gettype($value) == 'string') {
				$data[$index] = trim($value);
			}
		} 
		$data['messages']['name'] = $validator->setString($data['name'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'page_name_notnull'
																)
														);
		$data['messages']['slug'] = $validator->setString($data['slug'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'page_slug_notnull'
																)
														);
		$data['messages']['language'] = $validator->setString($data['language'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'page_language_notnull'
																)
														);
														
		$descriptionTemp = Gio_Core_String::stripTags($data['description'], null);
		$data['messages']['description'] = $validator->setString($descriptionTemp)
												->validate(array('notNull')
																, array(
																	'notNull' => 'page_description_notnull',
																)
														);
														
		$contentTemp = Gio_Core_String::stripTags($data['content'], null);
		$data['messages']['content'] = $validator->setString($contentTemp)
												->validate(array('notNull')
																, array(
																	'notNull' => 'page_content_notnull',
																)
														);
														
		$error = false;
		foreach ($data['messages'] as $index => $message) {
			if ($message) {
				$data['messages_error'] = true;
				return $data;
			}
		}										
		$data['messages_error'] = false;
		return $data;
	}
	
	public static function activate($page)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		$page['modified_date'] = date('Y-m-d H:i:s');
		$dao->update($page);
	}
	
	/**
	 * @param int $id
	 * @return array
	 */
	public static function getById($id)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		return $dao->getById($id);
	}
	
	public static function getBySlug($slug, $pageId = null)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		return $dao->getBySlug($slug, $pageId);
	}
	
	/**
	 * @param Page_Models_Page $page
	 * @return int
	 */
	public static function add($page, $sourceItem = null)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		
		$id  = $dao->add($page);
		
		/**
		 * Translation
		 */
		$json 		 = new Services_JSON();
		$source 	 = (array)$json->decode($sourceItem);
		$translation = array(
							'item_id' 	      => $id,
							'item_class'      => get_parent_class($dao),
							'source_item_id'  => (!isset($source['id']) || $source['id'] == '') ? $id : $source['id'],
							'language'        => $page['language'],
							'source_language' => (!isset($source['language']) || '' == $source['language']) ? null : $source['language'],
					);
		Modules_Core_Services_Translation::add($translation);
		return $id;
	}
	
	public static function count($condition = array())
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		return $dao->count($condition);
	}
	
	/**
	 * @param int $id
	 * @return bool
	 */
	public static function delete($page)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		
		if ($page != null) {
			$dao->delete($page);
			Modules_Core_Services_Translation::delete($page['page_id'], get_parent_class($dao));
		}
		
		return true;
	}
	
	/**
	 * @param array $page
	 * @return bool
	 */
	public static function update($page, $oldParentId = null, $sourceItem = null)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
				
		/**
		 * Get parent page
		 */
		$parent = ($page['parent_id']) ? $dao->getById($page['parent_id']) : null;
		if ((null == $parent && (int)$oldParentId == 0) || ($parent != null && (int)$oldParentId == (int)$page['parent_id'])) {
			/**
			 * User do NOT change the parent page value
			 */
			$dao->update($page);
		} else {
			/**
			 * User changed parent page
			 */
			$dao->delete($page);
			$pageId = $dao->add($page);
			/**
			 * Reset parent id
			 */
			$dao->updateParents($page['language']);
		}
		
		/**
		 * Translation
		 */
		$json 		 = new Services_JSON();
		$source 	 = (array)$json->decode($sourceItem);
		$translation = array(
							'item_id' 	      => $page['page_id'],
							'item_class'      => get_parent_class($dao),
							'source_item_id'  => (!isset($source['page_id']) || $source['page_id'] == '') ? $page['page_id'] : $source['page_id'],
							'language'        => $page['language'],
							'source_language' => (!isset($source['language']) || '' == $source['language']) ? null : $source['language'],
					);
		
		$sourceItem 	 = $json->decode($sourceItem);
		if ($sourceItem != null) {
			$translation['source_item_id'] = $sourceItem->id;
			$translation['source_language'] = $sourceItem->language;
		}
		
		if ($source != null) {
			Modules_Core_Services_Translation::update($translation);
		} else {
			Modules_Core_Services_Translation::add($translation);
		}
		
		return true;
	}
	
	/**
	 * @param array $page
	 * @return array
	 */
	public static function getSource($page)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		
		return $dao->getSource($page);	
	}
	
	/**
	 * @param string $lang
	 * @return array
	 */
	public static function getTree($lang = null)
	{
		$lang = (null == $lang) ? Gio_Core_Config_Xml::getConfig('web')->language : $lang;
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setLang($lang);
		$dao->setConnection($conn);
		return $dao->getTree();
	}
	
	/**
	 * @param array $data
	 */
	public static function updateOrder($page)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		
		$dao->updateOrder($page);
	}
	
	/**
	 * Get parent pages
	 * 
	 * @param int $id Id of page
	 * @return array
	 */
	public static function getParents($id, $lang = null)
	{
		$lang = ($lang) ? $lang : Gio_Core_Config_Xml::getConfig('web')->language;
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		return $dao->getParents($id, $lang);
	}
	
	public static function pageSelect($attributes = array(), $lang = 'vi_VN')
	{
		if (null == $lang) {
		}
		$json = new Services_JSON();
		
		$pages = self::getTree($lang);
		$selectedId = isset($attributes['selected']) ? $attributes['selected'] : null;
		$disableId  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$id = isset($attributes['id']) ? $attributes['id'] : null;
		$name = isset($attributes['name']) ? $attributes['name'] : null;
		
		$output 	= sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'>", 
							$attributes['name'],
							$attributes['id'],
							'Modules_Page_Services_Page::pageSelect',
							$json->encodeUnsafe($attributes)) . self::EOL
					. '<option value="">---</option>' . self::EOL;
		
		foreach ($pages as $page) {
			$selected = ($selectedId == null || $selectedId != $page['page_id']) ? '' : ' selected="selected"';
			$disable  = ($disableId == null || $disableId != $page['page_id']) ? '' : ' disabled';
			$output  .= sprintf('<option value="%s"%s%s>%s</option>',
								$page['page_id'],
								$selected,
								$disable,
								str_repeat('---', $page['depth']) . $page['name']) . self::EOL;
		}
		$output .= '</select>' . self::EOL;

		return $output;
	}
	
	public static function translatablePage($attributes = array(), $lang = null)
	{
		$json = new Services_JSON();
		$defaultLang     = (string)Gio_Core_Config_Xml::getConfig('web')->language;
		$lang = (null == $lang) ? $defaultLang : $lang;
		$elementDisabled = (null == $lang || $lang == $defaultLang) ? ' disabled="disabled"' : '';
		
		$attributes['selected'] = isset($attributes['selected']) ? $attributes['selected'] : null;
		$attributes['disabled']  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$pages 	 = self::getTranslatable($lang);
		$output 		 = sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'%s>", 
								$attributes['name'], 
								$attributes['id'],
								'Modules_Page_Services_Page::translatablePage',
								$json->encodeUnsafe($attributes), 
								$elementDisabled) . self::EOL
						. '<option value=\'{"id": "", "language": ""}\'>---</option>' . self::EOL;
		
		foreach ($pages as $page) {
			$disabled = (0 == (int)$page['translatable'] 
							&& ((0 == (int)$attributes['disabled'] && $page['page_id'] != (int)$attributes['selected'])
								||
							((int)$attributes['disabled'] == (int)$attributes['selected'])))
						? ' disabled="disabled"' 
						: '';
			$selected = ($elementDisabled == ''
							&& $disabled == ''
							&& (int)$page['page_id'] == (int)$attributes['selected'])
						? ' selected="selected"' 
						: '';
			
			$output  .= sprintf("<option value='%s'%s%s>%s</option>", 
								$json->encodeUnsafe(array('id' => $page['page_id'], 'language' => $defaultLang)), 
								$selected,
								$disabled,
								str_repeat('---', $page['depth']) . $page['name']) . self::EOL;
		}
		$output .= '</select>' . self::EOL;

		return $output;
	}
	
	public static function getTranslatable($lang)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Page_Models_Mysql_Page();
		$dao->setConnection($conn);
		return $dao->getTranslatable($lang);
	}
}
